package com.starinside.wp.interceptor;


import com.starinside.wp.domain.WxUser;
import com.starinside.wp.utils.DateUtil;
import com.starinside.wp.utils.IpHelper;
import com.starinside.wp.utils.ModelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.starinside.wp.foundation.constant.RequestConstant.TICKET;


/**
 * *******************************
 * Created by Tim.
 * form com.matt
 * on 2017/5/18
 * *******************************
 */
@Slf4j
@Component
public class ActionLogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI();

        String ip = IpHelper.getRequestIpAddr(request);

        WxUser loginUser = (WxUser) request.getSession().getAttribute("loginUser");

        String params = ModelUtil.objectMapper.writeValueAsString(request.getParameterMap());
        String loginUserStr = ModelUtil.objectMapper.writeValueAsString(loginUser);

        String ticket = request.getHeader(TICKET);
        if (StringUtils.isNotBlank(ticket)){
            log.info("request TICKET:[{}]", ticket);
        }
        log.info("request URL:[{}] , PARAMS:[{}], IP :[{}], DATE:[{}]",  requestUrl, params, ip, DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        log.info("request USER:[{}]",  loginUserStr);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
